package gitee.derumin.lifeissohard.mixin;

import gitee.derumin.lifeissohard.lishhungersystem.LishHungerManager;
import gitee.derumin.lifeissohard.tools.PlayerEntityTools;
import net.minecraft.server.PlayerManager;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.world.GameRules;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

@Mixin(PlayerManager.class)
public abstract class PlayerManagerMixin {

    @Redirect(method = "respawnPlayer" , at = @At(value = "INVOKE" , target = "Lnet/minecraft/server/network/ServerPlayerEntity;copyFrom(Lnet/minecraft/server/network/ServerPlayerEntity;Z)V" , ordinal = 0))
    private void copyHungerManager(ServerPlayerEntity newPlayer, ServerPlayerEntity oldPlayer, boolean alive){
        ((PlayerEntityTools)newPlayer).setHungerManager(oldPlayer.getHungerManager());
        if (!alive)((LishHungerManager)(newPlayer.getHungerManager())).reSet();
        newPlayer.copyFrom(oldPlayer , alive);
    }

    @Inject(method = "respawnPlayer" , at = @At(value = "HEAD"))
    private void dropInventory(ServerPlayerEntity player, boolean alive, CallbackInfoReturnable<ServerPlayerEntity> cir){
        if (!alive && !player.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY) && !player.isSpectator()){
            player.getInventory().dropAll();
        }
    }
}
